package team.you.change.service.serviceImpl;

import cn.dsna.util.images.ValidateCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import team.you.change.dao.TeacherMapper;
import team.you.change.dao.UserMapper;
import team.you.change.util.Result;
import team.you.change.pojo.Teacher;
import team.you.change.pojo.User;
import team.you.change.service.LoginService;
import team.you.change.util.Md5Util;
import team.you.change.util.Sendsms;
import team.you.change.util.YuoUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.regex.Pattern;

//服务层
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private TeacherMapper teacherMapper;

    //用户注册
    @Override
    public Result register(User user) {
        Result result = new Result();
        try {
            Result result1 = this.selUsername(user.getUsername());
            Result result2 = this.selTeaNo(user.getTeaNo());
            if (result1.getCode() == 0 && result2.getCode() == 0) {
                String id = UUID.randomUUID().toString(); //生成uuid
                String password = Md5Util.encryption(user.getUsername(), user.getPassword());//使用md5对密码加密
                User newUser = new User(id, user.getUsername(), password, "", "", user.getPhone(), "", "", user.getTeaNo(), 1);
                userMapper.insert(newUser);
                result.setMsg("注册成功");
                return result;
            } else {
                result.setCode(500);
                result.setMsg("用户名重复或工号被注册");
                return result;
            }
        } catch (Exception e) {
            return YuoUtil.setErrorMsg(e, result);
        }
    }

    //用户名重复验证
    @Override
    public Result selUsername(String value) {
        Result result = new Result();
        User user = userMapper.selectByUsername(value);
        if (user == null) {
            return result;
        } else {
            result.setCode(500);
            result.setMsg("此用户名以存在");
            return result;
        }
    }

    @Override
    public Result selTeaNo(String papers) {
        Result result = new Result();
        Teacher teacher = teacherMapper.selectByNo(papers);
        if(teacher != null){
            //检查此工号是否已被注册
            User user = userMapper.selectByTeano(papers);
            if(user == null){
                return result;
            }else{
                result.setCode(500);
                result.setMsg("此工号已被注册");
                return result;
            }
        }else{
            result.setCode(500);
            result.setMsg("此工号不存在");
            return result;
        }
    }

    @Override
    public void getCode(HttpServletRequest request, HttpServletResponse response) {
        //生成验证码
        ValidateCode validateCode=new ValidateCode(150,35,4,50);
        //获取验证码的验证信息 -后面登录时在服务层验证验证码正误
        String code = validateCode.getCode();
        //将code添加到session中
        request.getSession().setAttribute("code",code);
        //给session设置过期时间
        request.getSession().setMaxInactiveInterval(300);
        //通过输出流的方式，将验证码图片返回给前端
        try {
            validateCode.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Override
    public Result login(String remember, String username, String password, String code, HttpServletRequest request) {
        Result result = new Result();
//        String newCode = (String)request.getSession().getAttribute("code");//获取验证码
//        if(newCode.equalsIgnoreCase(code)){
//        username = "yuo";password = "123456abc";
            String regexp = "1(3|4|5|6|7|8|9)\\d{9}$"; //定义正则表达式
            User user;
            if(Pattern.matches(regexp, username)){
                user = userMapper.selectByPhone(username); // 通过手机号查询用户信息
            }else{
                user = userMapper.selectByUsername(username); // 通过用户名查询用户信息
            }
            if(user != null){
                String pwd = Md5Util.encryption(user.getUsername(), password); //将密码加密后与数据库中数据比对
                if(pwd.equals(user.getPassword())){ // 判断密码
                    request.getSession().setAttribute("user",user); // 设置session
                    if(remember.equals("1")){ //记住密码，保留登录状态24小时
                        request.getSession().setMaxInactiveInterval(60*60*24);
                    }
                    else request.getSession().setMaxInactiveInterval(60*10);
                    List<User> userList = new ArrayList<>();
                    userList.add(user);
                    result.setData(userList); //返回用户信息
                    return result;
                }else{
                    result.setCode(500);
                    result.setMsg("用户名或密码错误！");
                    return result;
                }
            }else{
                result.setCode(500);
                result.setMsg("用户名或密码错误！");
                return result;
            }
//        }else{
//            result.setCode(500);
//            result.setMsg("验证码错误！");
//            return result;
//        }
    }

    @Override
    public Result mobileCode(String phone, HttpServletRequest request) {
        Result result = new Result();
        User user = userMapper.selectByPhone(phone);
        if(user == null){
            Result sms = Sendsms.send(phone);
            if( sms.getCode()== 0){
                Integer mobileCode = sms.getCount();
                request.getSession().setAttribute("mobileCode", mobileCode);
                request.getSession().setMaxInactiveInterval(300);
                result.setMsg("短信发送成功");
                return result;
            }else {
                result.setCode(500);
                result.setMsg("短信发送失败");
                return result;
            }
        }else{
            result.setCode(400);
            result.setMsg("此手机号已被使用");
            return result;
        }
    }

    @Override
    public Result codeVarify(String testCode, Integer type, HttpServletRequest request) {
        Result result = new Result();
        String code;
        if (type == 0){
            code = request.getSession().getAttribute("mobileCode").toString();
        }else {
            code = request.getSession().getAttribute("emailCode").toString();
        }
        if(code != null && testCode.equals(code)){
            return result;
        }else {
            result.setCode(500);
            result.setMsg("验证码过期或有误！");
            return result;
        }
    }
}
